import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:winkai/entity/vip_product_info.dart';
import 'package:winkai/helper/iap/iap_helper.dart';
import 'package:winkai/helper/service_conf_helper.dart';
import 'package:winkai/service/api_service.dart';

class VipController extends GetxController {
  factory VipController() {
    _singleton ??= VipController._();
    return _singleton!;
  }

  static VipController? _singleton;

  VipController._();

  final List<ProductDetails> _rawProductList = [];
  List<VipProductInfo> vipProductList = [];
  VipProductInfo? currentSelect;
  List<String> banners = [];

  @override
  void onInit() {
    super.onInit();
    loadData();
  }

  void loadData() async {
    var result = await Future.wait<dynamic>([
      ApiService().getVipBanners(),
      IAPHelper().getProducts(),
    ]);

    List<String>? bannerList = result[0];
    if (bannerList?.isNotEmpty == true) {
      banners.addAll(bannerList!);
    }
    List<ProductDetails>? productList = result[1];
    if (productList?.isNotEmpty == true) {
      _rawProductList.addAll(productList!);
      var list = productList.map((e) => VipProductInfo.fromProduct(e)).toList();
      vipProductList.clear();
      vipProductList.addAll(list);
    }
    currentSelect = vipProductList.firstWhereOrNull((element) =>
        element.isYear == ServiceConfHelper().isDefaultVipSelectYear);
    update();
  }

  Future<void> restorePurchases() {
    return IAPHelper().restorePurchases();
  }

  void subscribeVip() {
    var productDetails = _rawProductList
        .firstWhereOrNull((element) => element.id == currentSelect?.productId);
    if (productDetails == null) {
      return;
    }
    IAPHelper().purchases(productDetails);
  }
}
